package com.onlinelibrary.activities.map;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.onlinelibrary.activities.App;
import com.onlinelibrary.activities.position.PositionActivity;
import com.onlinelibrary.activities.web.WebActivity;
import com.onlinelibrary.bean.ButtonBean;
import com.onlinelibrary.bean.MapBean;
import com.onlinelibrary.databinding.ActivityMapBinding;
import com.onlinelibrary.utils.Http;
import com.onlinelibrary.view.MapView;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MapVM extends AndroidViewModel {
    public static MutableLiveData<String>floor=new MutableLiveData<>();
    public static MutableLiveData<MapBean> map=new MutableLiveData<>();
    public static MutableLiveData<List<ButtonBean>> bbs=new MutableLiveData<>();
    @SuppressLint("StaticFieldLeak")
    private static MapActivity mapActivity;
    public MapVM(@NonNull Application application) {
        super(application);
        floor.setValue("");
        bbs.setValue(new ArrayList<>());
        map.setValue(new MapBean(null,null,null));
    }
    public void setBinding(ActivityMapBinding binding, MapActivity mapActivity) {
        MapVM.mapActivity=mapActivity;
        Http.get("position/map/?type=getDetail&library=" + App.position + "&floor=" + App.floor, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {

                    assert response.body() != null;
                    JSONObject data = new JSONObject(response.body().string()).getJSONObject("data");
                    String image=Http.BASE_URL+data.getJSONObject("floors").getString("image");
                    String fullImg=Http.BASE_URL+data.getJSONObject("floors").getString("fullImg");
                    JSONArray jsonArray = data.getJSONArray("points");
                    List<ButtonBean> buttonBeans = new ArrayList<>();
                    for(int i = 0 ; i < jsonArray.length() ; i++){
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        buttonBeans.add(new ButtonBean(jsonObject.getInt("x")/10000.,jsonObject.getInt("y")/10000.,jsonObject.getString("pos"),jsonObject.getString("order")));
                    }
                    bbs.postValue(buttonBeans);
                    map.postValue(new MapBean(buttonBeans,image,fullImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    @BindingAdapter("bindMap")
    public static void bindMap(MapView mapView,MutableLiveData<MapBean>map){
        if (map.getValue()!=null&&map.getValue().buttonBeans!=null&&map.getValue().image!=null){
            mapView.init(map.getValue().image,map.getValue().buttonBeans);
        }
    }
    @BindingAdapter("bindSpinner")
    public static void bindSpinner(Spinner spinner, MutableLiveData<List<ButtonBean>>buttonBeans){
        List<String> list=new ArrayList<>();
        list.add("请选择要游览的地点");
        for (ButtonBean buttonBean: Objects.requireNonNull(buttonBeans.getValue())) {
            list.add(buttonBean.content);
        }
        String[] items = list.toArray(new String[0]);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(mapActivity, android.R.layout.simple_spinner_item,items );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position!=0){
                    try {
                        JSONObject jo=new JSONObject();
                        jo.put("position",items[position]);
                        Http.post(jo, "visit/", new Callback() {
                            @Override public void onFailure(@NotNull Call call, @NotNull IOException e){}
                            @Override public void onResponse(@NotNull Call call, @NotNull Response response){}
                        });
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                    spinner.setSelection(0);
                    mapActivity.startActivity(new Intent(mapActivity, PositionActivity.class).putExtra("pos",items[position]));
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });
    }
    public static void fullImg(View view){
        String url=map.getValue().fullImg;
        if (url!=null&&!url.equals("")) {
          App.url="file:///android_asset/index.html?url="+url;
          mapActivity.startActivity(new Intent(mapActivity, WebActivity.class));
        }else {
            Toast.makeText(mapActivity, "加载失败", Toast.LENGTH_SHORT).show();
        }
    }
}